package jwei.apps;

import java.util.List;

import jwei.apps.adapters.StylesCursorAdapter;
import jwei.apps.db.StyleDb;
import jwei.apps.db.StyleCache.StylesCache;
import jwei.apps.objects.Style;
import jwei.apps.zappos.ZapposAutocomplete;
import jwei.apps.zappos.ZapposSearch;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class SearchZapposActivity extends ListActivity {

    private ProgressDialog pd;

    private StylesCursorAdapter scA;

    private AutoCompleteTextView autoText;

    private Button search;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_layout);

        search = (Button) findViewById(R.id.search_button);
        autoText = (AutoCompleteTextView) findViewById(R.id.search_bar);
        autoText.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                String term = autoText.getText().toString();
                if (term.length() > 1 && event.isPrintingKey()) {
                    new AutoCompleteZapposTask().execute(term);
                }
                return false;
            }

        });

        autoText.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // find which string was clicked on
                TextView autoTerm = (TextView) view.findViewById(R.id.auto_term);
                String str = autoTerm.getText().toString();
                // search this string
                new SearchZapposTask().execute(str);
            }

        });

        search.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String term = autoText.getText().toString();
                if (term.length() > 0) {
                    new SearchZapposTask().execute(term);
                } else {
                    Toast t = Toast.makeText(SearchZapposActivity.this, "Please enter a search term.",
                            Toast.LENGTH_SHORT);
                    t.show();
                }
            }

        });
    }

    private class SearchZapposTask extends AsyncTask<String, String, List<Style>> {

        @Override
        protected void onPreExecute() {
            pd = ProgressDialog.show(SearchZapposActivity.this, "Searching",
                    "Please wait while we search our inventory...", true, false);
        }

        // param[0] is search term
        protected List<Style> doInBackground(String... param) {
            List<Style> ret = ZapposSearch.searchTerm(param[0]);
            Log.i("SearchZapposActivity", "FOUND " + ret.size() + " RESULTS");
            return ret;
        }

        protected void onProgressUpdate(String... progress) {
            pd.setMessage(progress[0]);
        }

        protected void onPostExecute(List<Style> results) {
            if (results.size() > 0) {
                // save styles into cache
                StyleDb sdb = StyleDb.getInstance();
                sdb.refreshCache(getContentResolver());
                sdb.addStyles(getContentResolver(), results);

                // query for products
                Cursor c = getContentResolver().query(StylesCache.CONTENT_URI, null, StylesCache.IS_QUEUE + "= 0",
                        null, null);
                startManagingCursor(c);
                Log.i("SearchZapposActivity", "QUERIED " + c.getCount() + " STYLES FROM CACHE");
                String[] from = new String[] { StylesCache.PRODUCT_NAME, StylesCache.BRAND_NAME };
                int[] to = new int[] { R.id.product_name, R.id.brand_name };

                // create cursor adapter
                scA = new StylesCursorAdapter(SearchZapposActivity.this, R.layout.product_list_entry, c, from, to);

                // set as current list
                setListAdapter(scA);
            } else {
                Toast t = Toast.makeText(SearchZapposActivity.this,
                        "Could not retrieve desired products - check back with Zappos in a bit!", Toast.LENGTH_SHORT);
                t.show();
            }
            if (pd.isShowing()) {
                pd.dismiss();
            }
        }
    }

    private class AutoCompleteZapposTask extends AsyncTask<String, String, List<String>> {

        @Override
        protected void onPreExecute() {
        }

        // param[0] is uncompleted search term
        protected List<String> doInBackground(String... param) {
            List<String> ret = ZapposAutocomplete.searchTerm(param[0]);
            return ret;
        }

        protected void onProgressUpdate(String... progress) {
        }

        protected void onPostExecute(List<String> results) {
            if (results.size() > 0) {
                ArrayAdapter<String> aa = new ArrayAdapter<String>(SearchZapposActivity.this,
                        R.layout.search_auto_entry, results);
                autoText.setAdapter(aa);
            }
        }
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        if (scA == null) { return; }

        Cursor c = (Cursor) scA.getItem(position);

        Intent i = new Intent(SearchZapposActivity.this, ProductDetailsActivity.class);
        long productId = c.getLong(c.getColumnIndex(StylesCache.PRODUCT_ID));
        i.putExtra("productId", productId);
        i.putExtra("productName", c.getString(c.getColumnIndex(StylesCache.PRODUCT_NAME)));
        i.putExtra("productUrl", c.getString(c.getColumnIndex(StylesCache.PRODUCT_URL)));
        i.putExtra("brandName", c.getString(c.getColumnIndex(StylesCache.BRAND_NAME)));
        i.putExtra("imageUrl", c.getString(c.getColumnIndex(StylesCache.IMAGE_URL)));
        i.putExtra("styleId", c.getLong(c.getColumnIndex(StylesCache.STYLE_ID)));
        i.putExtra("price", c.getString(c.getColumnIndex(StylesCache.PRICE)));
        startActivity(i);
    }

}
